package com.myhome.money.base.javaio;

import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 文件随机读写
 */
public class FileRandomAccess {

    public static void main(String[] args) throws IOException {
        fileRandomRead();
        fileRandomWrite();
        fileRandomRead();
    }

    public static void fileRandomRead() throws IOException {
        RandomAccessFile accessFile = new RandomAccessFile("D:/javaio/io/test.txt", "rw");
        //移动读写位置
        accessFile.seek(10L);
        //文件开始位置
        long begin = accessFile.getFilePointer();
        byte[] contents = new byte[1024];
        accessFile.read(contents);
        String str = new String(contents);
        System.out.println("开始读取的位置：" + begin + ",结果;" + str);
        accessFile.close();
    }

    public static void fileRandomWrite() throws IOException {
        RandomAccessFile accessFile = new RandomAccessFile("D:/javaio/io/test.txt", "rw");
        accessFile.seek(accessFile.length());
        String str = " 这个是新添加的东西";
        accessFile.write(str.getBytes());
        accessFile.close();
    }

}
